var pageBean = null;
var dataList = {};
var currentData = null;
var currentBannerId = null;



$(document).ready(function(e) {
	$(".select2").uedSelect({
		width : 345  
	});
	$("#btnSave").click(save);
	$("#btnCancle").click(cancle);
	$("#bannerAdd").click(add);
	$("#bannerType").change(bannerTypeChange);
	$("#uploadFile").change(uploadSpaceImage);
	$("#uploadFile2").change(uploadSpaceImage2);
	search(1);	 
});

function uploadSpaceImage2(){
	
	var fileName = $("#uploadFile2").val();
	
	var dom = document.getElementById("uploadFile2");
	var fileSize = dom.files[0].size;
	if (fileSize > 10000000) {
		alert("上传文件过大,请上传小于10M的图片");
		$("#uploadFile").val("");
		return false;
	}
	var fileType = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLocaleLowerCase();
	if (fileType != 'jpg' && fileType != 'bmp' && fileType != 'png' && fileType != 'gif' && fileType != "jpeg") {
		alert("图片只能上传JPG,JPEG,BMP,PNG,GIF格式的图片！");
		$("#uploadFile").val("");
		return false;
	}
	
	var accessToken = localStorage.getItem('accessToken');
	$('#noticeImageForm2').ajaxSubmit({
		dataType : "json",
		headers : {'Access-Control-Allow-Origin':'*',"accessToken":accessToken},
		beforeSubmit : function(request) { 
			//alert("正在上传"); 
		}, 
		success : function(result, textStatus, response) { 
			if(result.status==0){
				editor.insertHtml('<p><img src="'+result.fileUrl+'"></p>');
			}
			
		},
		error : function(result) {
			//alert('上传失败！'); 
		} 
	});
}

function bannerTypeChange(){	
	var bannerType = $(this).children('option:selected').val();
	if(bannerType == '0'){
		$("#bannerUrl").show();
		$("#bnnerDetail").hide();
		$("#bannerUrlInput").attr("required","1");
		$("#bannerUrlInput").attr("message","请输入url");
		$("#content7").removeAttr("required");
		$("#content7").removeAttr("message");
	}else{
		$("#bannerUrl").hide();
		$("#bnnerDetail").show();
		$("#content7").attr("required","1");
		$("#content7").attr("message","请输入详情");
		$("#bannerUrlInput").removeAttr("required");
		$("#bannerUrlInput").removeAttr("message");
	}
}

function uploadSpaceImage(){
	 var fileName = $("#uploadFile").val();
		
	 var dom = document.getElementById("uploadFile");
	 var fileSize = dom.files[0].size;
	 if (fileSize > 10000000) {
		 alert("上传文件过大,请上传小于10M的图片");
		 $("#uploadFile").val("");
		 return false;
	}
	var fileType = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLocaleLowerCase();
	if (fileType != 'jpg' && fileType != 'bmp' && fileType != 'png' && fileType != 'gif' && fileType != "jpeg") {
		alert("图片只能上传JPG,JPEG,BMP,PNG,GIF格式的图片！");
		$("#uploadFile").val("");
		return false;
	}

	var accessToken = localStorage.getItem('accessToken');
	$('#bannerImageForm').ajaxSubmit({
		dataType : "json",
		headers : {'Access-Control-Allow-Origin':'*',"accessToken":accessToken},
		beforeSubmit : function(request) { 
			// alert("正在上传");
		}, 
		success : function(result, textStatus, response) { 
			// alert(JSON.stringify(result));
			$("#bannerImage").prop("src",result.fileUrl);
			$("input[name='bannerImage']").val(result.fileUrl);
			$("[formParameter='banner'][name='url']").val(result.fileUrl);
			// alert('成功上传！');
		},
		error : function(result) {
			// alert('上传失败！');
		} 
	});
}

function getRequestJson(data){	
	if(data == null){
		data = {};
	}	
	$type =$("#bannerType").val();
	$("[formParameter='banner']").each(function(index,element){		
		try{			
			var required = $(element).prop("required");	
			var name = $(element).attr("name");	
			var val =  $(element).val();
			
			if(name == "content"){
				val = window.editor.html() ;
			}
			if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
				var message = $(element).attr("message");
				alert(message);
				data = false;
				return false;
			}			
			data[name] = val;
		}catch(e){
			console.log(e.messge);
		}
	});	
	
	if($type==0){
		data['content']=$("#t4").val();
	}

	if($.trim(data["status"]) == ''){
		data["status"] = '1';
	}
	if($.trim(data["personName"]) == ''){
		data["personName"] = '';
	}
	if($.trim(data["id"]) == ''){
		data["id"] = '-1';
	}
	return data;
}

function save(){
	if($.trim(currentBannerId) == ''){
		currentData = {};
	}else{
		currentData = dataList[currentBannerId];
	}	
	currentData = getRequestJson(currentData);
	if(currentData == false){
		return false;
	}	
	var requestJson = {"data":currentData};
	$.ajax({
        url: '/euc/onlineops/banner/aoe',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	//console.log(JSON.stringify(datas));
        	if(datas.status == 0){
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	currentData = null;
            	currentBannerId = '';
            	search(pageBean.currentPage);
            	alert("保存成功！");
        	}else{
        		alert("保存失败！");
        	}
        },
        error: function () {
        	console.log('/euc/onlineops/banner/aoe error');
        }
    });
}

function cancle(){
	$("DIV[name='dataList']").show();
	$("DIV[name='dataForm']").hide();
}

function clearForm(){
	$("[formParameter='banner']").each(function(index,element){		
		try{			
			
			var name = $(element).attr("name");	
			if(name == "contentType"){
				$("bannerType").val(0).trigger('change');
			}else if(name == "content"){
				window.editor.html('');	
			}else{
				$(element).val('');
			}
		}catch(e){
			console.log(e.messge);
		}
	});
}

function setForm(data){
	if(data == null){
		data = {};
	}	
	$("[formParameter='banner']").each(function(index,element){		
		try{
			//console.log(element);
			var name = $(element).attr("name");	
			if(name == "contentType"){
				$("#bannerType").val(data[name]).trigger('change');
			}else if(name == "content"){
				window.editor.html(data[name]);
				
			}else if(name == "url"){				
				$("#bannerImage").prop("src",data[url]);
				$("input[name='bannerImage']").val(data[url]);
				$("#content9").val(data[content]);	
							
			}else{
				$(element).val(data[name]);
			}
		}catch(e){
			console.log(e.messge);
		}
	});
	return data;
}

function add(){
	currentData = null;
	$("#roleOperator").html("添加");
	clearForm();
	$("DIV[name='dataList']").hide();
	$("DIV[name='dataForm']").show();
}


function detail(id){
	currentData = dataList[id];
	currentBannerId = id;
	clearForm();
	// setForm(currentData);
	$("#t1").val(currentData['title']);
	$("#t2").val(currentData['orderNum']);
	if(currentData['url']){
		$("#bannerImage").attr('src',currentData['url']);
		$("#t3").val(currentData['url']);
	}
	if(currentData['contentType']==1){
		$("#bannerType").val(1).trigger('change');
		window.editor.html(currentData['content']);
	}else{
		$("#bannerType").val(0).trigger('change');
		$("#t4").val(currentData['content']);
	}
	
	

	
	$("#roleOperator").html("编辑");
	$("DIV[name='dataList']").hide();
	$("DIV[name='dataForm']").show();	
}


function deleteData(id){
	 if(confirm("确定删除该记录?")){
		var requestJson = {data:{"id":id}};
		$.ajax({
	        url: '/euc/onlineops/banner/delete',
	        data:JSON.stringify(requestJson),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType: 'JSON',
	        async: true,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	if(result.status == '0'){
	        		var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					search(cur);
	        		alert("删除成功！");
	        	}else{
	        		alert("删除失败！");
	        	}
	        },
	        error: function () {
	        	console.log('/euc/onlineops/banner/delete  error');
	        }  
	    });
	 }
}

function initailPageNumber(totalPage,currentPage,pageLength){				
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){

					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					// alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){/* alert(e.messge); */}	
}

function search(currentPage){
	
	var parameter = $("INPUT[name='parameter']").val();
	var requestJson = {currentPage:currentPage,data:{}};
		
	$.ajax({
        url: '/euc/onlineops/banner/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//console.log(JSON.stringify(result));
        	pageBean = result.data;
        	$("#dataTable").empty();	        	
        	$.each(result.data.list,function(i,data){
		        var contentType = $.trim(data.contentType);
		        if(contentType != ''){
		        	contentType = $("#bannerType option[value=" + contentType + "]").text()
		        }
        		var html = '<tr>';
        		html += '<td style="width:30px;"><input rowchecked name="'+data.id+'" type="checkbox" value="" /></td>';
        		html += '<td style="width:70px;">' + (i+1) + '</td>';
        		html += '<td style="width:160px;">' + $.trim(data.title) + '</td>';
        		html += '<td>' + contentType + '</td>';
        		html += '<td>' + data.orderNum + '</td>';
        		html += '<td>' + data.addTime + '</td>';
        		html += '<td>' + data.personName + '</td>';
        		html += '<td style="width:170px;"><a href="javascript:detail('+data.id+');" class="tablelink">编辑</a>&nbsp;&nbsp;&nbsp;<a href="javascript:deleteData('+data.id+');" class="tablelink">删除</a></td>';
        		html += '</tr>';
	        	$("#dataTable").append(html);
	        	dataList[data.id] = data;
			});
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	console.log("error");
        }  
    });
}

